package com.liu.common.aspect;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.liu.common.interfases.PrintLogInterface;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Aspect
@Component
public class PrintLogAspect {

    @Before("@annotation(printLogInterface)")
    public void before(JoinPoint joinPoint, PrintLogInterface printLogInterface) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        log.info("执行类：【{}】中的方法：【{}】，入参为：【{}】 开始", className, methodName,
                args != null && CollUtil.isNotEmpty(Arrays.asList(args)) ? JSONUtil.toJsonStr(args) : "");
    }

    @AfterReturning(value = "@annotation(printLogInterface)", returning = "result")
    public void afterReturning(JoinPoint joinPoint, PrintLogInterface printLogInterface, Object result) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        log.info("执行类：【{}】中的方法：【{}】，入参为：【{}】 结束，返回的结果为：【{}】", className, methodName,
                args != null && CollUtil.isNotEmpty(Arrays.asList(args)) ? JSONUtil.toJsonStr(args) : "",
                Objects.nonNull(result) ? JSONUtil.toJsonStr(result) : "");
    }

}
